package com.working.wanandroid.main.backup

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.working.libbase.base.WebViewActivity
import com.working.libbase.dialog.Dialog
import com.working.libbase.model.BackUpModel
import com.working.libbase.model.BackupChangeEvent
import com.working.libbase.storage.Storage
import com.working.libcommon.bus.LiveDataBus
import com.working.libcommon.exts.onClick
import com.working.wanandroid.databinding.ItemBackupBinding

class BackupAdapter :
    ListAdapter<BackUpModel, BackupAdapter.ViewHolder>(object :
        DiffUtil.ItemCallback<BackUpModel>() {
        override fun areItemsTheSame(oldItem: BackUpModel, newItem: BackUpModel): Boolean {
            return oldItem.title == newItem.title
        }

        override fun areContentsTheSame(oldItem: BackUpModel, newItem: BackUpModel): Boolean {
            return oldItem == newItem
        }

    }) {

    private val onDelete = { context: Context, position: Int ->
        Dialog.showConfirm(context, message = "确认删除此书签吗？", onOk = {
            Storage.backUpList = Storage.backUpList?.apply {
                removeAt(position)
            }
            LiveDataBus.send(BackupChangeEvent(null, position))
        })
    }

    private val onClick = { backup: BackUpModel ->
        WebViewActivity.start(backup.title.toString(),backup.url!!,backup.anchor)
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemBackupBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position), position, onDelete,onClick)
    }

    class ViewHolder(private val binding: ItemBackupBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(
            item: BackUpModel,
            position: Int,
            onDelete: (Context, Int) -> Unit,
            onClick: (BackUpModel) -> Unit
        ) {
            binding.item = item
            binding.delete.onClick {
                onDelete.invoke(itemView.context, position)
            }
            binding.image.onClick { onClick.invoke(item)}
            binding.executePendingBindings()
        }
    }
}